package day13;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: 王丹
 * @create: 2021-07-06 09:58
 **/
//await(long time, TimeUnit unit)超时之前被唤醒
public class Demo6 {

    static ReentrantLock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    public static class T extends Thread {
        public void run() {
            lock.lock();
            try {
                System.out.println(System.currentTimeMillis() + "," + this.getName() + ":start");
                boolean await = condition.await(5, TimeUnit.SECONDS);
                System.out.println(await);
                System.out.println(System.currentTimeMillis() + "," + this.getName() + ":end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
                System.out.println("lock.unlock()");
            }
        }
    }

    /**
     * 结果分析：t1线程中调用 condition.await(5,TimeUnit.SECONDS);方法会释放锁，等待5秒，主线程休眠1秒，
     * 然后获取锁，之后调用signal()方法唤醒t1，输出结果中发现await后过了1秒（1、3行输出结果的时间差），
     * await方法就返回了，并且返回值是true。true表示await方法超时之前被其他线程唤醒了。
     */
    public static void main(String[] args) throws InterruptedException {
        T t1 = new T();
        t1.setName("t1");
        t1.start();

        TimeUnit.SECONDS.sleep(1);
        lock.lock();
        try {
            condition.signal();
        } finally {
            lock.unlock();
            System.out.println(Thread.currentThread().getName() + " lock.unlock()");
        }

    }

}
